package com.apes.framework.config.elasticsearch;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.springframework.boot.actuate.health.Health;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

public class ApesElasticsearchHealthIndicator {
    private final String[] ALL_INDICES = new String[]{"_all"};
    private final Client client;
    private final long responseTimeout;
    private final String[] indices;

    public ApesElasticsearchHealthIndicator(Client client, long responseTimeout, List<String> indices) {
        this.client = client;
        this.responseTimeout = responseTimeout;
        this.indices = StringUtils.toStringArray(indices);
    }

    public Health health() {
        Health.Builder builder = new Health.Builder();
        try {
            ClusterHealthRequest request = Requests.clusterHealthRequest(ObjectUtils.isEmpty(this.indices) ? ALL_INDICES : this.indices);
            ClusterHealthResponse response = this.client.admin().cluster().health(request).actionGet(this.responseTimeout);
            switch (response.getStatus()) {
                case GREEN:
                case YELLOW:
                    builder.up();
                    break;
                case RED:
                default:
                    builder.down();
            }
        } catch (Exception var4) {
            builder.down(var4);
        }
        return builder.build();
    }
}
